/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using XMLPushStreamBase = System.Qizx.Xdm.XMLPushStreamBase;
using System.Qizx.XQuery;
using ArraySequence = System.Qizx.XQuery.Dt.ArraySequence;
using ErrorValue = System.Qizx.XQuery.Impl.ErrorValue;
namespace System.Qizx.XQuery.Op
{
	
	public class TypeswitchExpr:Expression
	{
		public override int Flags
		{
			get
			{
				return updating?UPDATING:0;
			}
			
		}
		public Expression switche;
        internal TypeCaseClause[] caseClauses;
		internal bool updating;
		
		public TypeswitchExpr(Expression on)
		{
			this.switche = on;
		}

        public virtual void addCaseClause(TypeCaseClause clause)
		{
			if (caseClauses == null)
                caseClauses = new TypeCaseClause[] { clause };
			else
			{
                TypeCaseClause[] old = caseClauses;
                caseClauses = new TypeCaseClause[old.Length + 1];
				Array.Copy(old, 0, caseClauses, 0, old.Length);
				caseClauses[old.Length] = clause;
			}
		}

        internal virtual TypeCaseClause getCaseClause(int rank)
		{
			return rank < 0 || rank >= caseClauses.Length?null:caseClauses[rank];
		}
		
		public override Expression Child(int rank)
		{
			return (rank == 0)?switche:((rank <= caseClauses.Length)?caseClauses[rank - 1]:null);
		}
		
		public override void  Dump(ExprDisplay d)
		{
			d.header(this);
			d.child("on", switche);
			d.children(caseClauses);
		}
		
		public override Expression StaticCheck(ModuleContext context, int flags)
		{
			int nupCount = 0;
			switche = context.staticCheck(switche, 0);
			
			type = null;
			for (int c = 0, C = caseClauses.Length; c < C; c++)
			{
				context.simpleStaticCheck(caseClauses[c], 0);
				if (type == null)
					type = caseClauses[c].getType();
				else
					type = type.unionWith(caseClauses[c].getType(), true);
				
				if (caseClauses[c].updating)
					updating = true;
				else if (!UpdatingExpr.isNeutral(caseClauses[c].expr))
					++nupCount;
			}
			// TODO: detect switch on single item -> optimizable
			// TODO: optimize by hashing, grouping by kind etc...
			
			if (updating && nupCount > 0)
				context.error("XUST0001", this, "mix of updating and non-updating " + "expressions in typeswitch");
			return this;
		}
		
		public override XQValue eval(Focus focus, EvalContext context)
		{
			XQValue value_Renamed = switche.eval(focus, context);
			context.at(this);
			ArraySequence seq = new ArraySequence(8, value_Renamed);
			XQItem singleItem = null;
			for (; value_Renamed.Next(); )
				seq.addItem(singleItem = value_Renamed.Item);
			seq.pack();
			
			// optimize if exactly one item: the occurence will always match
			bool oneItem = seq.Size == 1;
			
			// brute force implementation: TODO
			for (int c = 0, C = caseClauses.Length; c < C; c++)
			{
                TypeCaseClause cc = caseClauses[c];
				XQType testType = cc.declaredType;
				bool ok;
				if (oneItem)
					ok = testType.acceptsItem(singleItem);
				else
				{
					seq.reset();
					ok = !(seq.CheckTypeExpand(testType, context, false, false) is ErrorValue);
				}
				if (ok)
				{
					seq.reset();
					if (cc.variable != null)
						context.storeLocal(cc.varDecl.address, seq, false, null); // already
					// checked
					return cc.expr.eval(focus, context);
				}
			}
			throw new System.SystemException("Typeswitch default failed"); // should
			// not
			// happen
		}
		
		public override void  EvalAsEvents(XMLPushStreamBase output, Focus focus, EvalContext context)
		{
			XQValue value_Renamed = switche.eval(focus, context);
			context.at(this);
			ArraySequence seq = new ArraySequence(8, value_Renamed);
			XQItem singleItem = null;
			for (; value_Renamed.Next(); )
				seq.addItem(singleItem = value_Renamed.Item);
			seq.pack();
			
			// optimize if exactly one item: the occurence will always match
			bool oneItem = seq.Size == 1;
			
			// brute force implementation: TODO
			for (int c = 0, C = caseClauses.Length; c < C; c++)
			{
                TypeCaseClause cc = caseClauses[c];
				XQType testType = cc.declaredType;
				bool ok;
				if (oneItem)
					ok = testType.acceptsItem(singleItem);
				else
				{
					seq.reset();
					ok = !(seq.CheckTypeExpand(testType, context, false, false) is ErrorValue);
				}
				if (ok)
				{
					seq.reset();
					if (cc.variable != null)
						context.storeLocal(cc.varDecl.address, seq, false, null); // already
					// checked
					cc.expr.EvalAsEvents(output, focus, context);
					break;
				}
			}
		}
	}
}